package com.ht.managermentserver.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ht.managermentserver.entity.SysUser;
import com.ht.managermentserver.service.SysUserService;
import com.ht.managermentserver.sysenum.ErrorCode;
import com.ht.managermentserver.utils.JsonResult;
import com.ht.managermentserver.utils.JwtTokenUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录模块
 *
 * @author czy
 * @package com.ht.managermentserver.controller
 * @date 2020/5/30 13:44
 */
@Api(tags = "登录模块")
@RestController
@RequestMapping("login")
@Slf4j
public class LoginController extends BaseController {

  @Autowired OAuth2RestTemplate auth2RestTemplate;

  @Autowired HttpServletRequest httpServletRequest;

  @Autowired SysUserService userService;

  @GetMapping("/getLoginUser")
  public JsonResult<Map<String, Object>> getLoginUser() {
    final String authorization = httpServletRequest.getHeader(JwtTokenUtil.TOKEN_HEADER);
    final Long userId = JwtTokenUtil.getUserId(authorization);
    final SysUser user = userService.getById(userId);
    final Map<String, Object> result = new HashMap<>(2);
    result.put("authorization", authorization);
    result.put("user", user);
    return JsonResult.create("success", ErrorCode.SUCCESS, result);
  }

  @PostMapping("/login")
  public JsonResult<Map<String, Object>> login(
      @RequestParam final String username, @RequestParam final String password) {

    if (StringUtils.isEmpty(password) || StringUtils.isEmpty(username)) {
      return JsonResult.create("用户名或密码不能为空", ErrorCode.ERROR);
    }

    final QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
    wrapper.eq(SysUser.USER_NAME, username);
    final SysUser user = userService.getOne(wrapper);
    if (user.getPassWord().equals(password)) {
      final String authorization = JwtTokenUtil.createJwtToken(user);
      final Map<String, Object> result = new HashMap<>(2);
      result.put("authorization", authorization);
      result.put("user", user);
      return JsonResult.create("登陆成功", ErrorCode.SUCCESS, result);
    } else {

      return JsonResult.create("用户名或密码错误", ErrorCode.ERROR);
    }
  }
}
